package com.wondertek.poms.service.config;

import cn.hutool.core.date.DateUtil;
import com.wondertek.oes.sso.common.util.StringUtil;
import com.wondertek.poms.dao.po.EquityTreeMQLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 * @author evan0213
 * @description
 */
@Configuration
@Slf4j
public class ActiveMQConverter implements MessageConverter {
	@Autowired
	private Queue pomsTreeQueue;

	@Override
	public Message toMessage(Object obj, Session session) throws JMSException, MessageConversionException {
		if (obj instanceof EquityTreeMQLog) {
			EquityTreeMQLog equityTreeMQLog = (EquityTreeMQLog) obj;
			StringBuffer sb = new StringBuffer();
			sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			sb.append("<MsgText>");
			//TransactionCode = key + 'V' + version
			sb.append("<id>").append(equityTreeMQLog.getId()).append("</id>");
			sb.append("<type>").append(equityTreeMQLog.getType()).append("</type>");
			sb.append("<pushContentId>").append(equityTreeMQLog.getPushContentId()).append("</pushContentId>");
			sb.append("<oprCode>").append(equityTreeMQLog.getOprCode()).append("</oprCode>");
			sb.append("<xmlName>").append(equityTreeMQLog.getXmlName()).append("</xmlName>");
			sb.append("<OprTime>").append(DateUtil.format(equityTreeMQLog.getOprTime(), "yyyyMMddHHmmss")).append("</OprTime>");
			sb.append("</MsgText>");
			String msg = sb.toString();
			log.info("EquityTreeMQLog的id为{}", equityTreeMQLog.getId());
			log.info(msg);
			try {
				TextMessage txtMsg = session.createTextMessage();
				txtMsg.setJMSReplyTo(pomsTreeQueue);
				txtMsg.setText(msg);
				return txtMsg;
			} catch (Exception e) {
				log.error("Send message[" + StringUtil.null2Str(equityTreeMQLog.getId()) + "] error:", e);
				throw new JMSException("Send message[" + StringUtil.null2Str(equityTreeMQLog.getId()) + "] error !");
			}
		} else {
			log.error("Object: [" + obj + "] is not a Message !");
			throw new JMSException("Object: [" + obj + "] is not a Message !");
		}
	}

	@Override
	public Object fromMessage(Message msg) throws JMSException, MessageConversionException {
		if (msg instanceof TextMessage) {

			return ((TextMessage) msg).getText();
		} else {
			throw new JMSException("Message: [" + msg + "] is not a TextMessage !");
		}
	}
}
